package com.taplinker.client.im.rpc;

import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;

import com.taplinker.app.LoginActivity;
import com.taplinker.client.AppConfigContext;
import com.taplinker.client.AppConfigFactory;
import com.taplinker.client.core.LocalFileManager;
import com.taplinker.client.core.LoginHistoryManager;
import com.taplinker.client.domain.LoginUser;
import com.taplinker.client.domain.MenuDomain;
import com.taplinker.client.domain.UserInfo;
import com.taplinker.client.im.SocketTemplateContext;
import com.taplinker.client.im.activity.IMQueueActivity;
import com.taplinker.client.im.domain.ImDataCenter;
import com.taplinker.client.widget.DrawerGarment;
import com.taplinker.core.rpc.Result;
import com.taplinker.core.rpc.RpcClientContext;
import com.taplinker.core.rpc.command.SimpleBaseCommand;
import com.taplinker.core.rpc.http.HttpTemplate;
import com.taplinker.dto.web.LoginRequest.LoginProtoReq;
import com.taplinker.dto.web.LoginRequest.LoginProtoReq.Builder;
import com.taplinker.dto.web.LoginResponse;
import com.taplinker.dto.web.LoginResponse.LoginProtoRes;
import com.taplinker.sdk.core.TapLinkerClient;

public class LoginCmd extends SimpleBaseCommand {
	private String userName;
	private String password;
	private Handler handler;

	public LoginCmd(String userName, String password, Context context,
			Handler handler) {
		super(context);
		this.userName = userName;
		this.password = password;
		super.context = context;
		this.handler = handler;
	}

	@Override
	public Result go() {
		Builder res = LoginProtoReq.newBuilder();
		res.setAccount(userName);
		res.setPassword(password);
		return new HttpTemplate().postForGogoByte(
				AppConfigContext.TAPLINKER_WEB + "/services/auth/signup", res
						.build().toByteArray());
	}

	@Override
	public void yes(Result result) {
		try {
			handler.sendEmptyMessage(0);
			LoginProtoRes data = LoginResponse.LoginProtoRes
					.parseFrom((byte[]) result.object);
			UserInfo user = new UserInfo();
			user.setUserName(data.getUsername());
			user.setUserIcon(data.getIcon());
			user.setRole(data.getRoleList());
			user.setToken(data.getToken());
			user.setEmail(data.getEmail());
			user.setPhone(data.getPhone());
			user.setUserid(Long.valueOf(data.getUserid()));
			user.setImToken(data.getToken());
			user.setNickname(data.getNickname());
			// 初始化应用参数
			AppConfigFactory.getInstance().setAppKey(data.getAppKey());
			AppConfigFactory.getInstance().setUserInfo(user);
			AppConfigFactory.getInstance().setWebDisk(data.getUrl());
			LocalFileManager.getInstance().ayscCreateDirs();
			RpcClientContext.getInstance().setCookies(
					"TAPLINKER_TOKEN=" + data.getToken());
			((LoginActivity) super.context).closeProgressDialog();
			SocketTemplateContext.getInstance().initialize(
					context.getApplicationContext());

			// 初始化左侧导航栏
			Intent intent = null;
			MenuDomain.resetMenuClickable();
			if (!user.isRole("ROOT_SUPER")) {
				if (user.isRole("IM")) {
					MenuDomain.open(MenuDomain.MenuItems.PUBLIC);
					ImDataCenter.getInstance().setPublicQueue(true);
					intent = new Intent(super.context, IMQueueActivity.class);
					new SwitchToken().execute();
				}
			} else {
				intent = new Intent(super.context, IMQueueActivity.class);
				new SwitchToken().execute();
			}
			DrawerGarment.initOpen = true;
			TapLinkerClient.registerDevice(registerContent(user));
			super.context.startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private HashMap<String, String> registerContent(UserInfo user) {
		HashMap<String, String> result = new HashMap<String, String>();
		result.put("enterprise_appkey",
				"19581e27de7ced00ff1ce50b2047e7a567c76b1cbaebabe5ef03f7c3017bb5b7");
		if (user.getRole().contains("IM_ADMIN")) {
			result.put("im_admin", "IM_ADMIN");
		} else {
			result.put("im_admin", "NULL");
		}

		if (user.getRole().contains("IM_STANDARD")) {
			result.put("im_standard", "IM_STANDARD");
		} else {
			result.put("im_standard", "NULL");
		}

		if (user.getRole().contains("CRM_ADMIN")) {
			result.put("crm_admin", "CRM_ADMIN");
		} else {
			result.put("crm_admin", "NULL");
		}

		if (user.getRole().contains("CRM_STANDARD")) {
			result.put("crm_standard", "CRM_STANDARD");
		} else {
			result.put("crm_standard", "NULL");
		}

		result.put("account", user.getUserName());
		return result;
	}

	@Override
	public void no(Result result) {
		handler.sendEmptyMessage(0);
		((LoginActivity) super.context).closeProgressDialog();
		if (result.status == 400 && super.context != null) {
			LoginHistoryManager.getInstance().reset(super.context,
					new LoginUser(userName));
		} else {
			super.no(result);
		}
	}
}
